﻿using Core.Bind;
using System;
using System.Collections.Generic;

namespace Core
{
    using Dict = Dictionary<IBind, Dictionary<IBind, Bind.IBinder>>;

    public class BindSystem : Component, IAwake
    {
        private readonly Dict dict = new();

        public void Awake()
        {

        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

        }

        private bool Contains(IBind target, IBind source)
        {
            if (dict.ContainsKey(target) == false)
            {
                return false;
            }
            var dic = dict[target];
            return dic.ContainsKey(source);
        }

        private Bind.IBinder Get(IBind target, IBind source)
        {
            if (Contains(target, source) == false)
            {
                return null;
            }
            return dict[target][source];
        }

        private void Add(IBind target, IBind source, Bind.IBinder binder)
        {

        }

        private void Remove(IBind target, IBind source)
        {

        }

        /// <summary>
        /// 显示数据源到文本
        /// </summary>
        /// <param name="target"></param>
        /// <param name="source"></param>
        public void Bind(IBindText target, IBindDBVar source)
        {
            if (Contains(target, source))
            {
                log.err($"重复绑定，target={target} source={source}");
                return;
            }

            var binder = G.Factory.Create<TextBinder>();
            binder.Target = target;
            binder.Source = source;
            binder.Bind();

            Add(target, source, binder);
        }

        /// <summary>
        /// 格式化绑定Int与Text，
        /// format:
        ///     timer：时间格式
        /// </summary>
        /// <param name="target"></param>
        /// <param name="source"></param>
        /// <param name="format"></param>
        public void Bind(IBindText target, DSInt source, string format = "")
        {
            if (Contains(target, source))
            {
                log.err($"重复绑定，target={target} source={source}");
                return;
            }

            var binder = G.Factory.Create<IntegerFormatBinder>();
            binder.Target = target;
            binder.Source = source;
            binder.Format = format;
            binder.Bind();

            Add(target, source, binder);
        }

        public void Bind(UIButton target, Action func)
        {
            var binder = G.Factory.Create<ButtonClickBinder>();
            binder.Target = target;
            binder.Func = func;
            binder.Bind();

        }

        public void UnBind(IBindText target, IBindDBVar source)
        {

        }

    }
}
